from django.http import JsonResponse

from .enums import SCE


class R(object):
    """
    统一项目信息返回结果
    """

    def __init__(self):
        self.status = None
        self.error = None
        self.success = None
        self._data = []

    @staticmethod
    def success(message=SCE.OK.errmsg):
        """
        组织成功响应信息
        :return:
        """
        r = R()
        r.status = 200
        r.success = {'message': message}
        return r

    @staticmethod
    def error(enum, data=None):
        """
        业务层面失败
        """
        r = R()
        r.status = 200
        if data is not None:
            if type(enum) == tuple:
                r.error = {'code': enum[0], 'message': data}
            else:
                r.error = {'code': enum.code, 'message': data}
        else:
            if type(enum) == tuple:
                r.error = {'code': enum[0], 'message': enum[1]}
            else:
                r.error = {'code': enum.code, 'message': enum.errmsg}
        return r

    @staticmethod
    def server_error():
        """
        组织服务器错误信息。直接返回500
        """
        r = R()
        r.status = SCE.SERVER_ERR.code
        r.error = {'code': SCE.SERVER_ERR.code, 'message': SCE.SERVER_ERR.errmsg}
        return r

    @staticmethod
    def db_error():
        """
        数据库异常
        """
        r = R()
        r.status = SCE.SERVER_ERR.code
        r.error = {'code': SCE.DB_ERR.code, 'message': SCE.DB_ERR.errmsg}
        return r

    # 手动指定状态码
    def status(self, status=200):
        self.status = status

    # 手动指定成功时的返回信息
    def message(self, message='返回信息模板'):
        self.success = {'message': message}

    # 手动指定要传回的数据，并直接返回结构体
    def data(self, data=None, data_name='data'):
        """统一后端返回的数据"""
        if data:
            self._data = data

        if self.error is not None:
            context = {
                'status': self.status,
                'error': self.error,
                data_name: self._data
            }
        else:
            context = {
                'status': self.status,
                'success': self.success,
                data_name: self._data
            }
        return JsonResponse(context)
